﻿using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

namespace Utility
{
    public class PrintHelper
    {
        public PrintHelper()
        {
        }

        public static void PrintWebControl(Control control)
        {
            PrintWebControl(control, string.Empty);
        }

        public static void PrintWebControl(Control control, string Script)
        {
            StringWriter stringWrite = new StringWriter();
            HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWrite);
            if (control is WebControl)
            {
                Unit w = new Unit(100, UnitType.Percentage);
                ((WebControl)control).Width = w;
            }
            Page pg = new Page();
            pg.EnableEventValidation = false;
            if (Script != string.Empty)
            {
                pg.ClientScript.RegisterStartupScript(pg.GetType(), "PrintJavaScipt", Script);
            }

            HtmlForm frm = new HtmlForm();
            pg.Controls.Add(frm);
            frm.Attributes.Add("runat", "server");
            frm.Controls.Add(control);
            pg.RenderControl(htmlWriter);
            string strHTML = stringWrite.ToString();
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Write(strHTML);
            HttpContext.Current.Response.Write("<script>window.print();</script>");
            HttpContext.Current.Response.End();
        }
    }
}